import { getAddressList } from '/api/address';

Page({
  data: {
    addressList: [],
    zm_user_id: '',
    id: '',
  },
  onLoad(option) {
    const zm_user_id = my.getStorageSync({ key: 'zm_user_id' }).data;
    this.setData({
      zm_user_id,
    });
    const { platform } = option
    let app = getApp();
    app.setShareChannel(platform)
  },
  onShow() {
    this.getAddressListData();
  },
  addNewAddress() {
    my.navigateTo({
      url: '../../rent/confirm-order/shopping-address/edit-address/edit-address'
    })
  },

  // 获取地址列表
  async getAddressListData() {
    const rst = await getAddressList({
      zm_user_id: this.data.zm_user_id,
    });

    const addressList =  rst.data.map(item => {
      const { provinces, city, district } = item
      if(!provinces || !city || !district) {
        item.update = true
      } else {
        item.update = false
      }
      return item
    });
    this.setData({
      addressList
    });
  },
  // 选择地址数据
  chooseAddress(e) {
    const id = e.target.dataset.id;
    this.setData({
      id
    })
    my.navigateBack();

  },
  // 修改地址
  edit(e) {
    const item = e.target.dataset.item;
    my.navigateTo({ url: `/page/mine/addAddress/addAddress?id=${item.id}` });
  },
  onUnload() {
    const { globalData } = getApp()
    globalData.addressId = this.data.id

    const { addressList } = this.data
    if(!addressList.length) {
      let pages = getCurrentPages(); // 当前页面
      let beforePage = pages[pages.length - 2]; // 上一页
      beforePage.setData({
        address_info: null
      })
    }
  },
  // 获取支付宝地址
  handleNewAddress() {
    my.getAddress({
      success: async (res) => {
        const { 
          address, 
          city, 
          fullname, 
          mobilePhone, 
          prov, 
          area = '',
        } = res.result;

        if (res.resultStatus == 9000) {
   
          const params = 
          `?receiver_name=${fullname}&receiver_phone=${mobilePhone}&address=${address}&district=${area}&city=${city}&provinces=${prov}`
          my.navigateTo({
            url: `/page/mine/addAddress/addAddress${params}`
          })
 
        } else {
          console.log('getAddress cancel', JSON.stringify(res));
        }
      },
      fail: () => {
        my.navigateTo({ url: '/page/mine/addAddress/addAddress' });
      },
    });
  },
});
